//
//  UIImage+JTExtension.m
//  百思不得姐
//
//  Created by Robin Zhang on 2017/1/14.
//  Copyright © 2017年 BeiJingWangDianJieTong. All rights reserved.
//

#import "UIImage+JTExtension.h"

@implementation UIImage (JTExtension)

/************************ 一.图片缩放 ************************/
/** 1.1 将图片缩放至规定的CGSize大小 */
- (instancetype)jt_imageCompressWithTargetScaledSize:(CGSize)size {
    
    UIGraphicsBeginImageContext(size);
    [self drawInRect:CGRectMake(0 ,0 , size.width, size.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

/** 1.2 将图片按比例缩放 */
- (instancetype)jt_imageCompressWithScale:(float)scale {
    
    CGSize size = self.size;
    CGFloat width = size.width;
    CGFloat height = size.height;
    
    CGFloat scaledWidth = width * scale;
    CGFloat scaledHeight = height * scale;
    
    UIGraphicsBeginImageContext(size); // thiswillcrop
    [self drawInRect:CGRectMake(0, 0, scaledWidth, scaledHeight)];
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage;
}

/** 1.3 将图片根据宽/高等比例缩放 */
- (instancetype)jt_imageCompressWithTargetScaledWidth:(CGFloat)width {
    
    return [self jt_imageCompressWithTargetScaledSize:CGSizeMake(width, (self.size.height / self.size.width) * width)];
}

- (instancetype)jt_imageCompressWithTargetScaledHeight:(CGFloat)height {
    
    return [self jt_imageCompressWithTargetScaledSize:CGSizeMake((self.size.width / self.size.height) * height, height)];
}

/*********************** 二.生成圆形图片 ***********************/
/** 返回圆形图片 */
- (instancetype)jt_circleImage {
    
    /*********** Quartz2D ***********/
    /******* 将方形UIImage转变成圆形UIImage(图形处理) *******/
    /**
     核心步骤：
     1.开启一个与图片大小相同的上下文；
     2.在上下文中添加一个最大的圆；
     3.裁剪；
     4.根据获得的圆将图片绘制成相应的形状；
     5.赋值绘制好的图片；
     6.关闭上下文。
     */
    // 1.开启图形上下文
    UIGraphicsBeginImageContext(self.size);
    
    // 2.上下文(获得当前的上下文)
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    // 3.添加一个圆(确认图片将被绘制的样子)
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    CGContextAddEllipseInRect(ctx, rect); // Ellipse:椭圆
    
    // 4.裁剪(将确认的样子的多余部分减除)
    CGContextClip(ctx);
    
    // 5.绘制图片(根据得到的样子绘制图片)
    [self drawInRect:rect];
    
    // 6.获得绘制后的图片并赋值给UIImageView
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 7.关闭上下文
    UIGraphicsEndImageContext();
    
    return newImage;
}

+ (instancetype)jt_circleImageNamed:(NSString *)name {
    
    return [[self imageNamed:name] jt_circleImage];
}

@end
